<template>
  <el-dialog v-model="dialogVisible" :title="title" width="60%" @close="handleClose">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" class="mt-4">
      <!-- 基本信息 -->
      <div class="mb-6">
        <div class="text-lg font-medium text-gray-700 mb-4">基本信息</div>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="接收人" prop="assigneerId">
              <el-input v-model="assigneerName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接收时间" prop="jobReceiveTime">
              <el-date-picker v-model="formData.jobReceiveTime" type="datetime" value-format="x" placeholder="选择任务接收时间"
                disabled />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="维修分类" prop="repairCategoryId">
              <el-select v-model="formData.repairCategoryId" placeholder="请选择维修分类">
                <el-option v-for="category in categoryList" :key="category.id" :label="category.name"
                  :value="category.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="实际开始时间" prop="taskStartTime">
              <el-date-picker v-model="formData.jobStartTime" type="datetime" value-format="x" placeholder="选择开始时间"
                @change="calculateWorkHours" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="实际结束时间" prop="taskEndTime">
              <el-date-picker v-model="formData.jobEndTime" type="datetime" value-format="x" placeholder="选择结束时间"
                @change="calculateWorkHours" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="实际工时(分)" prop="jobExecutionDuration">
              <div class="flex items-center">
                <el-input-number v-model="formData.jobExecutionDuration" :min="0" style="width: 100%" placeholder="自动计算"
                  :disabled="true" />
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="维修人" prop="repairerIds">
              <el-select clearable multiple filterable v-model="formData.repairerIds" placeholder="请选择维修人">
                <el-option v-for="dict in maintainerList" :key="dict.id" :label="dict.nickname" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input v-model="formData.description" type="textarea" :rows="2" placeholder="请输入备注"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { RepairCategoryApi } from '@/api/mold/repaircategory';
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import { RepairJobApi, RepairJobWorkReport } from '@/api/mold/repairjob';
import { getUserProfile } from '@/api/system/user/profile'

// 定义组件的 props
const props = withDefaults(defineProps<{
  title?: string
}>(), {
  title: '报工'
})

// 定义组件的 emits
const emit = defineEmits<{
  (e: 'success'): void
}>()
// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}
const dialogVisible = ref(false)
const submitting = ref(false)
// 表单引用
const formRef = ref()
const jobId = ref<number>(0)

// 接收人名称（用于显示）
const assigneerName = ref('')


// 维修人员列表
const maintainerList = ref<UserVO[]>([])

// 维修分类列表
const categoryList = ref([])

// 获取当前用户信息
const currentUser = ref<any>(null)

interface FormDataType {
  id: number
  assigneerId: string
  repairCategoryId: string
  jobReceiveTime: string
  jobStartTime: string
  jobEndTime: string
  jobExecutionDuration: number
  repairerIds: number[]
  description: string
  isCompleted: boolean
}

// 表单数据
const formData = reactive<FormDataType>({
  id: 0,
  assigneerId: '',
  repairCategoryId: '',
  jobReceiveTime: '',
  jobStartTime: '',
  jobEndTime: '',
  jobExecutionDuration: 0,
  repairerIds: [],
  description: '',
  isCompleted: false
})



// 重置表单
const resetForm = () => {
  formData.id = 0
  formData.assigneerId = ''
  formData.repairCategoryId
  formData.jobReceiveTime = ''
  formData.jobStartTime = ''
  formData.jobEndTime = ''
  formData.jobExecutionDuration = 0
  formData.repairerIds = []
  formData.description = ''
  formData.isCompleted = false
  assigneerName.value = ''
}

// 计算工时
const calculateWorkHours = () => {
  if (formData.jobStartTime && formData.jobEndTime) {
    const startTime = new Date(parseInt(formData.jobStartTime)).getTime()
    const endTime = new Date(parseInt(formData.jobEndTime)).getTime()

    if (startTime >= endTime) {
      ElMessage.warning('实际结束时间必须大于实际开始时间')
      formData.jobExecutionDuration = 0
      return
    }

    // 计算分钟数，使用四舍五入保持与RepairAccountAudit.vue中calculateActualDuration方法一致
    const duration = (endTime - startTime) / (1000 * 60)
    const roundedDuration = Math.round(duration)
    formData.jobExecutionDuration = roundedDuration
  }
}




// 打开弹窗方法
const open = async (id: number) => {
  await getMaintainerList()
  await getCategoryList()
  try {
    resetForm()
    jobId.value = id
    // 调用接口查询需要的数据
    const result = await RepairJobApi.getRepairJob(id)

    // 填充表单数据
    formData.id = result.id
    formData.assigneerId = result.assigneerId ? result.assigneerId.toString() : ''
    formData.jobReceiveTime = result.jobReceiveTime || ''
    formData.jobStartTime = result.jobStartTime || ''
    formData.jobEndTime = result.jobEndTime || Date.now()

    // 设置接收人名称
    const assigneer = maintainerList.value.find(user => user.id === result.assigneerId)
    assigneerName.value = assigneer ? assigneer.nickname : ''

    // 如果有开始时间和结束时间，则计算工时
    if (formData.jobStartTime && formData.jobEndTime) {
      calculateWorkHours()
    }

    // 获取当前用户信息并设置为默认维修人
    const currentUser = await getUserProfile()
    if (currentUser && currentUser.id) {
      formData.repairerIds = [currentUser.id]
    }

    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取任务信息失败')
    console.error('获取任务信息失败:', error)
  }
}

defineExpose({
  open
})

const handleSubmit = async () => {
  try {
    submitting.value = true
    await formRef.value?.validate()

    // 验证实际开始和结束时间
    if (formData.jobStartTime && formData.jobEndTime) {
      const startTime = new Date(parseInt(formData.jobStartTime)).getTime()
      const endTime = new Date(parseInt(formData.jobEndTime)).getTime()
      if (startTime >= endTime) {
        ElMessage.error('实际结束时间必须大于实际开始时间')
        submitting.value = false
        return
      }
    }

    // 准备提交数据
    const submitData: RepairJobWorkReport = {
      id: formData.id,
      repairCategoryId: formData.repairCategoryId,
      repairerIds: formData.repairerIds,
      jobStartTime: formData.jobStartTime,
      jobEndTime: formData.jobEndTime,
      jobExecutionDuration: formData.jobExecutionDuration,
      description: formData.description,
      repairCost: 0 // 默认维修费用为0
    }

    // 发送请求
    await RepairJobApi.submitWorkReport(submitData)

    ElMessage.success('报工成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请检查表单')
  } finally {
    submitting.value = false
  }


}


// 获取保养人员列表
const getMaintainerList = async () => {
  try {
    maintainerList.value = await UserApi.getSimpleUserList()
  } catch (error) {
    ElMessage.error('获取保养人员列表失败')
    console.error(error)
  }
}


// 获取维修分类列表
const getCategoryList = async () => {
  try {
    categoryList.value = await RepairCategoryApi.getRepairCategoryAll()
  } catch (error) {
    ElMessage.error('获取维修分类列表失败')
    console.error(error)
  }
}

const formRules = reactive({
  repairCategoryId: [{ required: true, message: '维修分类不能为空', trigger: 'change' }],
  jobStartTime: [{ required: true, message: '实际开始时间不能为空', trigger: 'change' }],
  jobEndTime: [{ required: true, message: '实际结束时间不能为空', trigger: 'change' }],
  jobExecutionDuration: [{ required: true, message: '实际工时不能为空', trigger: 'blur' }],
})


</script>